//
//  KakaSettingViewController.swift
//  NewsItem
//
//  Created by mac on 2023/7/13.
//  Copyright © 2023 Kaka. All rights reserved.
//
import UIKit

class Plant_SettingViewController: BasicViewController {

    let arr = ["Term of us","Privacy Policy","Delete Account","Clear cache","Version"]
    private lazy var table: UITableView = {
        let view = UITableView(frame: .zero, style: .plain)
        view.separatorStyle = .none
        view.backgroundColor = .clear
        view.delegate = self
        view.dataSource = self
        view.showsVerticalScrollIndicator = false
        view.register(SettingTableViewCell.self, forCellReuseIdentifier: "cell")
        view.rowHeight = 60.Fit
        return view
    }()
    let outB = UIButton.initV(font: .setTypeFace(18.Fit,type: .bold), text: "Sign out", img: "sigonout")
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = false
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        title = "Setting"
        view.subviews {
            table.subviews {
                outB
            }
        }
        table.fillContainer()
        outB.width(screenWidth - 30.Fit).height(50.Fit).left(15.Fit).top(350.Fit)
        outB.setAllCorners(corner: 25.Fit)
        outB.setTitleColor(mainColor, for: .normal)
        outB.backgroundColor = .blackComponent(0.3)
        outB.addAct {
            AgoraRTMClient.shared._kit?.logout()
            let vc = Pet_LoginHomeViewController()
            UIApplication.shared.keyWindow?.rootViewController = NavigationInterface(rootViewController: vc)
            UserDefaults.standard.setValue(nil, forKey: USERINFOKEY)
        }
        
    }

    func getCacheSize() -> String {
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        // 取出文件夹下所有文件数组
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        //快速枚举出所有文件名 计算文件大小
        var size = 0
        for file in fileArr! {
            
            // 把文件名拼接到路径中
            let path = cachePath! + ("/\(file)")
            // 取出文件属性
            let floder = try? FileManager.default.attributesOfItem(atPath: path)
            // 用元组取出文件大小属性
            if floder != nil {
                for (key, fileSize) in floder! {
                    // 累加文件大小
                    if key == FileAttributeKey.size {
                        size += (fileSize as AnyObject).integerValue
                    }
                }
            }
        }
        let totalCache = Double(size) / 1024.00 / 1024.00
        return String(format: "%.1fM", totalCache)
    }

}

extension Plant_SettingViewController:UITableViewDelegate,UITableViewDataSource{
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return arr.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SettingTableViewCell
        cell.selectionStyle = .none
        cell.nameLabel.text = arr[indexPath.row]
        if arr[indexPath.row] == "Clear cache" {
            cell.morelabel.isHidden = false
            cell.more.isHidden = true
            cell.morelabel.text = self.getCacheSize()
        }else if arr[indexPath.row] == "Version" {
            cell.morelabel.isHidden = false
            cell.more.isHidden = true
            cell.morelabel.text = "V1.0.2"
        }else
        {
            cell.morelabel.isHidden = true
            cell.more.isHidden = false
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        switch arr[indexPath.row] {
        case "Term of us":
            let vc = WkWebViewController()
            vc.urlstr = termUrl
            vc.str = "Terms of us"
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case "Privacy Policy":
            let vc = WkWebViewController()
            vc.urlstr = policeUrl
            vc.str = "Privacy Policy"
            vc.hidesBottomBarWhenPushed = true
            self.navigationController?.pushViewController(vc, animated: true)
            break
        case "Clear cache":
            self.clearCache()
            tableView.reloadData()
            break
        case "Delete Account":
            let view1 = Delete_View()
            let page = Pop_Up_Custom_View(config: PopUpViewConfig(view: view1, size: CGSize(width: screenWidth, height: screenHeight)))
            page.isCloseFromClean = false
            page.animatedPop()
            break
        default:
            break
        }
    }
    
    func clearCache() {
        Toast_View_Tool.show()
        // 取出cache文件夹目录
        let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first
        let fileArr = FileManager.default.subpaths(atPath: cachePath!)
        // 遍历删除
        for file in fileArr! {
            let path = (cachePath! as NSString).appending("/\(file)")
            if FileManager.default.fileExists(atPath: path) {
                do {
                    try FileManager.default.removeItem(atPath: path)
                } catch {
                }
            }
        }
        Toast_View_Tool.show(type: .success,text: "Clean up completed!")
    }
    
}


class SettingTableViewCell: UITableViewCell {
    
    let more = UIImageView.initImgView(img: "more")
    let nameLabel = UILabel.initV(.setTypeFace(18,type: .bold), text: "", textColor: .white)
    let morelabel = UILabel.initV(.setTypeFace(18,type: .bold), text: "", textColor: .white)
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        backgroundColor = .clear
        selectionStyle = .none
        contentView.subviews {
            nameLabel
            more
            morelabel
        }
        more.width(12.Fit).height(17.Fit).right(15)
        more.centerVertically()
        morelabel.height(25.Fit).width(55.Fit).right(15.Fit)
        morelabel.centerVertically()
        nameLabel.left(15).top(15).height(30)
        nameLabel.Trailing == more.Leading - 20
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

class Delete_View: UIView {
    
    let backI = UIImageView.initImgView(img: "deleteBack")
    private var ttLabel = UILabel.initV(.setTypeFace(17.Fit,type: .extraBold), text: "Delete Account", textColor: titleColor)
    private lazy var descView: Custom_TextView = {
        let view = Custom_TextView()
        view.textContainerInset = UIEdgeInsets(top: 10.Fit, left: 10.Fit, bottom: 10.Fit, right: 10.Fit)
        view.tintColor = .black
        view.textColor = .black
        view.placeHolderColor = UIColor.blackComponent(0.8)
        view.placeHolder = "Tell us how we can do better"
        view.returnKeyType = .done
        view.font = .setTypeFace(16,type: .medium)
        view.backgroundColor = .clear
        return view
    }()
    lazy var cancelBtn: UIButton = {
        let l = UIButton(frame: .zero)
        l.setImage(.init(named: "closeIcon"), for: .normal)
        return l
    }()
    lazy var doneBtn: UIButton = {
        let l = UIButton(frame: .zero)
        l.backgroundColor = mainColor
        l.titleLabel?.font = .setTypeFace(20,type: .bold)
        l.addTarget(self, action: #selector(OkAction), for: .touchUpInside)
        l.setTitleColor(.black, for: .normal)
        l.setTitle("Delete Account", for: .normal)
        return l
    }()
    private var tipLabel = UILabel.initV(.setTypeFace(15,type: .system), text: "All your account information will be Deleted please consider carefully!", textColor: .color(hexString: "#E80000"))
    let backV = UIView.init(frame: .zero)
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = .clear
        self.subviews {
            backV.subviews {
                ttLabel
                backI
                descView
                doneBtn
                tipLabel
            }
            cancelBtn
        }
        
        backV.backgroundColor = .white
        backV.layer.cornerRadius = 42.Fit
        backV.layer.maskedCorners = .allCorner
        backV.left(40.Fit).right(40.Fit).height(366.Fit)
        backV.centerVertically()
        
        ttLabel.left(10.Fit).right(10.Fit).height(30.Fit).top(15.Fit)
        ttLabel.textAlignment = .center
        
        backI.left(15.Fit).right(15.Fit).height(160.Fit)
        backI.Top == ttLabel.Bottom + 20.Fit
        
        descView.left(15.Fit).right(15.Fit).height(160.Fit)
        descView.Top == ttLabel.Bottom + 20.Fit
        descView.setAllCorners(corner: 20.Fit)
        
        cancelBtn.size(40.Fit)
        cancelBtn.Top == backV.Bottom + 15.Fit
        cancelBtn.centerHorizontally()
        cancelBtn.addAct {
            self.superview?.animatedDismiss()
        }
        
        tipLabel.textAlignment = .center
        tipLabel.left(20.Fit).right(20.Fit).height(40.Fit).bottom(20.Fit)
        
        doneBtn.left(20.Fit).height(50.Fit).right(20.Fit)
        doneBtn.Bottom == tipLabel.Top - 10.Fit
        doneBtn.setAllCorners(corner: 25.Fit)
        doneBtn.addAct {
            RT.deletUserWith { str in
                AgoraRTMClient.shared._kit?.logout()
                self.superview?.animatedDismiss()
                UserDefaults.standard.setValue(nil, forKey: USERINFOKEY)
                // 登录界面
                UIApplication.shared.keyWindow?.rootViewController = UINavigationController(rootViewController: Pet_LoginHomeViewController())
            }
        }
        
    }
    
    @objc func OkAction() -> Void {
        
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
